package org.jadapter.servicelookup;

/**
 * Simple service locator abstraction.
 * 
 * The idea is that code can safely depend on this to look up
 * global services by type, name or both, and that a container-
 * specific implementation will actually implement the lookup.
 * 
 * There is a Spring implementation in org.jadapter.spring.
 * 
 * @author optilude
 *
 */
public class ServiceLookup {
	
	private static ServiceLookupDelegate delegate = null; 
	
	/**
	 * Set the lookup delegate. This <em>must</em> be set up
	 * by the container before any calls to lookupService() can
	 * be made.
	 * 
	 * @param delegate The current delegate
	 */
	public static void _setServiceLookupDelegate(ServiceLookupDelegate delegate) {
		ServiceLookup.delegate = delegate;
	}
	
	/**
	 * Get the current delegate
	 */
	public static ServiceLookupDelegate _getServiceLookupDelegate() {
		return delegate;
	}
	
	/**
	 * Look up a unique service by type
	 * @param type The type of service to look for
	 * @return The service of this type, or null if not found. 
	 */
	public static <T> T lookupService(Class<T> type) {
		if(delegate == null) {
			throw new RuntimeException("ServiceLookup has not been initialised");
		}
		
		return delegate.lookupService(type);
	}
	
	/**
	 * Look up a unique service by type and name
	 * @param type The type of service to look for
	 * @param name The name of the service instance to look for
	 * @return The service of this type, or null if not found. 
	 */
	public static <T> T lookupService(Class<T> type, String name) {
		if(delegate == null) {
			throw new RuntimeException("ServiceLookup has not been initialised");
		}
		
		return delegate.lookupService(type, name);
	}
	
}
